// import { postWorkflowApprovalProcessExplainCreate, IPostWorkflowApprovalProcessExplainCreateReq } from '@/api';
import { MciForm, MciTextarea } from '@/components/base';
import { TApprovalCarbonCopies } from '@/components/business/Approval/approval-helper';

// import { MciRichEditor } from '@/components/complex';
// import { getUserIdList } from '@/components/complex/RichEditor/components/Mention/useMention';

import { useUser } from '@/hooks/useUser';
// import { IVitalFormConfig, IVitalFormCtx, VitalForm } from 'vital';
import { InjectionKey, PropType } from 'vue';
import { approvalDateFormat, isEndActivity, isStartActivity, TItemData, TProgressTaskType } from '.';
import { useToggleIcon } from '..';
import { FormMode } from '@/components/base/Form/mode';

type TApprovalExplains = Required<TApprovalCarbonCopies[0]>['approvalExplains'];

interface IccInfoProvideCtx {
  mode: TVitalModeType;
}
export const ccInfoProvideKey = 'ccInfoProvideKey' as unknown as InjectionKey<IccInfoProvideCtx>;
// // 抄送内容
export const CCInfo = defineComponent({
  props: {
    list: {
      type: Array as PropType<TApprovalCarbonCopies>,
      default: () => []
    },
    activityDefinitionId: {
      type: String,
      default: ''
    },
    ccDate: {
      type: String,
      default: ''
    }
  },
  setup(props) {
    // const formRef = ref(null as TNullable<IVitalFormCtx<IPostWorkflowApprovalProcessExplainCreateReq>>);
    const formRef = ref(null);
    // const { getApprovalProgress, processInstanceId } = useApprovalProvide();
    const ccInfoConfig = inject(ccInfoProvideKey);

    const ccInfoMode = computed(() => {
      return ccInfoConfig?.mode || 'edit';
    });
    const { userId } = useUser().value;
    // const formConfig = ref<IVitalFormConfig<IPostWorkflowApprovalProcessExplainCreateReq>>({
    const formConfig = ref<any>({
      attrs: {},
      layout: { cols: 1 },
      formItems: [
        {
          attrs: {},
          rulePresets: {
            rules: [{ prefixMsg: '请输入内容', trigger: 'change', rule: 'required' }]
          },
          fields: [
            {
              prop: 'explainMsg',
              attrs: { mention: true, updateSelection: true },
              defaultValue: null,
              type: 'richEditor'
            }
          ]
        }
      ]
    });
    // 抄送人所在的组
    const findCarbon = computed(() => {
      return props.list.find((item) => item.recipients?.find((recipient) => recipient.userId === userId));
    });
    /** const getBusinessKey = () => {
      const data = findCarbon.value;
      if (data) {
        return data.emailTemplateType;
      }
      return '';
    };**/
   /** const handleSend = async () => {
      await formRef.value?.validate();
      const model = formRef.value!.getModel();
      const businessKey = getBusinessKey();

      await postWorkflowApprovalProcessExplainCreate({
        processInstanceId: processInstanceId.value,
        businessKey,
        activityDefinitionId: props.activityDefinitionId,
        explainMsg: model.explainMsg,
        repliedUserId: getUserIdList(model.explainMsg)
      });
      MciNotification.success('发送成功');
      formRef.value?.resetToDefault();
      // 重新查询数据
      getApprovalProgress();
    };**/
    // 抄送人
    const ccUsers = computed(() => {
      return props.list
        .filter((item) => !!item?.recipients?.length)
        .map((item) => {
          return item.recipients?.map((recipient) => recipient.userName).join('，');
        })
        .join('，');
    });
    // 是否有添加说明的权限：  抄送人 & 非审批历史
    const isHandleRole = computed(() => {
      return !!findCarbon.value && ccInfoMode.value === 'edit';
    });
    // 说明
    const approvalExplains = computed(() => {
      const list: TApprovalExplains = [];
      props.list.map((item) => {
        item.approvalExplains && list.push(...item.approvalExplains);
      });
      return list;
    });
    const msgTotal = computed(() => {
      return approvalExplains.value.length;
    });
    const descToggle = useToggleIcon();
    const addToggle = useToggleIcon();
    return {
      formRef,
      formConfig,
      descToggle,
      addToggle,
      // handleSend,
      ccUsers,
      msgTotal,
      approvalExplains,
      isHandleRole,
      findCarbon
    };
  },
  render() {
    const renderForm = () => {
      return (
        <>
        {/* TODO 替换Form组件 */}
          {/* <VitalForm ref="formRef" config={this.formConfig} mode="edit" class="mt-8" /> */}
          <FormMode mode='edit'>
          <MciForm ref="formRef"></MciForm>
          </FormMode>
          {/* <div class="flex justify-end -mt-8">
            <MciButton type="primary" size="small" onClick={this.handleSend}>
              发送
            </MciButton>
          </div> */}
        </>
      );
    };

    // const renderDescList = () => {
    //   return this.approvalExplains.map((explain) => {
    //     const { owner, createdTime, explainMsg } = explain;
    //     return (
    //       <div class="text-value-12 mt-8px">
    //         <div>{owner?.userName || ''}</div>
    //         <div class="text-label-12 mt-4 mb-4">{approvalDateFormat(createdTime)}</div>
    //         <MciRichEditor modelValue={explainMsg} mode="view" ellipsis={3} />
    //       </div>
    //     );
    //   });
    // };
    const renderDescList = () => {
      return this.approvalExplains.map((explain) => {
        const { owner, createdTime, explainMsg } = explain;
        return (
          <div class="text-value-12 mt-8px">
            <div>{owner?.userName || ''}</div>
            <div class="text-label-12 mt-4 mb-4">{approvalDateFormat(createdTime)}</div>
            {/* <MciRichEditor modelValue={explainMsg} mode="view" ellipsis={3} /> */}
            <MciTextarea modelValue={explainMsg} mode="view" ellipsis={3}></MciTextarea>
          </div>
        );
      });
    };

    // 只有抄送人有添加说明权限
    const renderAddDesc = () => {
      if (this.isHandleRole) {
        return (
          <div class="cursor-pointer" onClick={this.addToggle.handleToggle}>
            {this.addToggle.renderToggle()}
            <span class="cr-green-6 ml-2"> {this.$t('添加说明')}</span>
          </div>
        );
      }
      return null;
    };
    return (
      <div class="text-value-12 mt-8px">
        <div>{this.$t('抄送')}</div>
        <div class="mt-4">
          <span class="text-label-12">{this.$t('抄送至')}</span> <span>{this.ccUsers}</span>
          <div class="text-label-12 mt-4px mb-4">{approvalDateFormat(this.ccDate)}</div>
        </div>
        <div class="bg-grey-1 p-8 text-value-12 rounded-4 mt-4px">
          <div class="flex">
            <div class="mr-12 cursor-pointer" onClick={this.descToggle.handleToggle}>
              {this.descToggle.renderToggle()}
              <span class="ml-4 mr-2">{this.msgTotal}</span>
              {this.$t('条说明')}
            </div>
            {renderAddDesc()}
          </div>
          {this.addToggle.enable.value ? renderForm() : null}
          {this.descToggle.enable.value ? renderDescList() : null}
        </div>
      </div>
    );
  }
});

export const renderCCInfo = (type: TProgressTaskType, data?: TItemData) => {
  if (!data) return null;
  const { carbonCopies, activityDefinitionId } = data;
  let date = '';
  if (isStartActivity(type, data) || isEndActivity(type, data)) {
    date = data.endTime || '';
  } else {
    date = data.userTasks?.[0]?.startTime || '';
  }
  if (!!carbonCopies?.length) {
    return <CCInfo list={carbonCopies} activityDefinitionId={activityDefinitionId} ccDate={date} />;
  }
};
